package com.ruoyi.web.controller.crm;

import com.bonuo.crm.domain.Project;
import com.bonuo.crm.service.DeviceService;
import com.bonuo.crm.service.ProcessService;
import com.bonuo.crm.service.ProjectService;
import com.bonuo.crm.util.ProjectBigDecimalUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.bonuo.crm.util.ProjectBigDecimalUtil.paginateList;
import static com.bonuo.crm.util.ProjectBigDecimalUtil.sumBigDecimal;

//项目Controller
@RestController
@RequestMapping("/crm/project")
@Api(tags = "项目信息管理")
public class ProjectController extends BaseController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProcessService processService;
    @Autowired
    private DeviceService deviceService;

    //查询项目信息
    @GetMapping("/list")
    @ApiOperation(value = "查询项目信息", httpMethod = "GET")
    public AjaxResult list(Project project, Integer pageNum, Integer pageSize) {

        // 1. 查博诺下的项目（需排除的项目ID）
        List<Integer> bnProjectIds = projectService.selectBNProjectIds();

        // 2. 获取该人员可见的所有项目（分权限）
        List<Project> allVisibleProjects = projectService.selectProjectList(project);

        // 3. 筛选非博诺项目（排除内部项目）
        List<Project> nonBnProjects = allVisibleProjects.stream()
                .filter(proj -> !bnProjectIds.contains(proj.getId())) // 排除博诺项目
                .collect(Collectors.toList());

        // 4. 计算总预算金额、总中标金额、已中标项目的预算总和
        BigDecimal totalAmount = BigDecimal.ZERO;          // 总预算金额（非博诺）
        BigDecimal totalBidAmount = BigDecimal.ZERO;       // 总中标金额（非博诺）
        BigDecimal bidProjectsAmount = BigDecimal.ZERO;    // 已中标项目的预算总和（关键新增）

        // 收集非博诺项目的ID（用于后续查询终止项目）
        List<Integer> nonBnProjectIds = new ArrayList<>();

        for (Project proj : nonBnProjects) {
            nonBnProjectIds.add(proj.getId());

            // 累加总预算金额（处理null）
            if (proj.getAmount() != null) {
                totalAmount = totalAmount.add(proj.getAmount());
            }

            // 累加总中标金额（处理null）
            if (proj.getBidAmount() != null) {
                totalBidAmount = totalBidAmount.add(proj.getBidAmount());
            }

            // 累加已中标项目的预算金额（关键：如果项目已中标，其预算需从总预算中扣除）
            if (proj.getBidAmount() != null) { // 假设bidAmount不为null即表示已中标
                if (proj.getAmount() != null) {
                    bidProjectsAmount = bidProjectsAmount.add(proj.getAmount());
                }
            }
        }

        // 5. 计算已终止项目的预算金额总和（确保查询的是预算金额amount，而非其他字段）
        BigDecimal stopAmount = projectService.selectAmountByStop(nonBnProjectIds);
        // 处理stopAmount为null的情况
        if (stopAmount == null) {
            stopAmount = BigDecimal.ZERO;
        }

        // 6. 计算未开标金额：总预算 - 已中标项目的预算 - 已终止项目的预算
        BigDecimal unAmount = totalAmount.subtract(bidProjectsAmount).subtract(stopAmount);

        // 7. 分页查询项目列表（保持原有逻辑）
        if (pageNum != null && pageSize != null) {
            startPage();
        }
        List<Project> projectList = projectService.selectProjectList(project);

        // 8. 组装返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", getDataTable(projectList));
        map.put("totalAmount", totalAmount);
        map.put("totalBidAmount", totalBidAmount);
        map.put("unAmount", unAmount); // 替换为新计算的未开标金额
        map.put("stopAmount", stopAmount);

        return success(map);
    }

    //添加项目信息
    @PostMapping("/add")
    @ApiOperation(value = "添加项目信息",httpMethod = "POST")
    public AjaxResult add(@RequestBody Project project){
        //根据项目编号查询项目是否存在，没有编号根据名称
        if(project.getProjectNo()!=null && !project.getProjectNo().equals("")){
        String nameOrNo = projectService.selectProjectByProjectNameOrNo(project);
            if(nameOrNo != null && !nameOrNo.equals("")){
                return AjaxResult.error("项目编号已存在");
            }
        }
        //查询当月该学校院系中是否有三次
//        Integer check = projectService.selectProjectByContactIdAndMonth(project.getContactId());
//        if(check>=3){
//            return AjaxResult.error("该学校院系当月项目不能超过3个");
//        }
        Integer add = projectService.insertProject(project);
        return AjaxResult.success(add);
    }

    //查询当前项目名是否存在
    @GetMapping("/checkProjectNameUnique")
    @ApiOperation(value = "查询当前项目名是否存在",httpMethod = "GET")
    public AjaxResult checkProjectNameUnique(Project project){
        Integer check = projectService.selectProjectByProjectName(project.getName());
        if(check>0){
            return AjaxResult.success("项目已存在",1);
        }
        return AjaxResult.success("项目未存在",0);
    }

    //删除项目信息
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除项目信息",httpMethod = "DELETE")
    public AjaxResult delete(@PathVariable Integer id){
        //先查询对应的项目下有没有相应的跟单过程
        Integer process = processService.selectProcessByProjectFundId(id);
        if(process>0){
            return AjaxResult.warn("该项目下有相应的项目过程，不能删除");
        }
        //在查询该项目下是否有相应的设备信息
        Integer device = deviceService.selectDeviceByProjectId(id);
        if(device>0){
            return AjaxResult.warn("该项目下有相应的设备信息，不能删除");
        }
        Integer delete = projectService.deleteProjectById(id);
        return toAjax(delete);
    }

    //修改项目信息
    @PutMapping("/update")
    @ApiOperation(value = "修改项目信息",httpMethod = "PUT")
    public AjaxResult update(@RequestBody Project project){
        if(project.getProjectNo()!=null && !project.getProjectNo().equals("")){
            String nameOrNo = projectService.selectProjectByProjectNameOrNo(project);
            if(nameOrNo != null && !nameOrNo.equals("")){
                return AjaxResult.error("项目编号已存在");
            }
        }
        Integer update = projectService.updateProject(project);
        return toAjax(update);
    }

    //导出项目信息
    @PostMapping("/export")
    @ApiOperation(value = "导出项目信息",httpMethod = "POST")
    public void export(HttpServletResponse response,Project project){
        List<Project> projectList = projectService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        util.exportExcel(response,projectList, "项目数据");
    }

}
